<template>
  <view class="page-container">
    <!-- 加载状态 -->
    <view v-if="loading" class="loading-container">
      <view class="loading-spinner"></view>
      <text class="loading-text">加载中...</text>
    </view>

    <!-- 错误状态 -->
    <view v-else-if="error" class="error-container">
      <view class="error-icon">❌</view>
      <text class="error-text">{{ error }}</text>
      <button class="retry-btn" @click="loadEventDetail">重试</button>
    </view>

    <!-- 事件详情内容 -->
    <view v-else-if="event" class="event-detail">
      <!-- 事件头部信息 -->
      <view class="event-header">
        <view class="event-date-section">
          <view class="event-date">
            <text class="date-day">{{ formatDay(event.eventDate) }}</text>
            <text class="date-month">{{ formatMonth(event.eventDate) }}</text>
          </view>
          <view class="event-type-badge" :style="{ backgroundColor: event.color || '#007AFF' }">
            <text class="type-text">{{ getEventTypeText(event.eventType) }}</text>
          </view>
        </view>
        
        <view class="event-title-section">
          <text class="event-title">{{ event.title }}</text>
          <text v-if="event.description" class="event-description">{{ event.description }}</text>
        </view>
      </view>

      <!-- 事件详细信息 -->
      <view class="event-details">
        <!-- 时间信息 -->
        <view class="detail-item">
          <view class="detail-icon">🕐</view>
          <view class="detail-content">
            <text class="detail-label">时间</text>
            <text class="detail-value">{{ formatEventTime(event) }}</text>
          </view>
        </view>

        <!-- 地点信息 -->
        <view v-if="event.location" class="detail-item">
          <view class="detail-icon">📍</view>
          <view class="detail-content">
            <text class="detail-label">地点</text>
            <text class="detail-value">{{ event.location }}</text>
          </view>
        </view>

        <!-- 提醒信息 -->
        <view v-if="event.reminderMinutes" class="detail-item">
          <view class="detail-icon">🔔</view>
          <view class="detail-content">
            <text class="detail-label">提醒</text>
            <text class="detail-value">{{ formatReminderText(event.reminderMinutes) }}</text>
          </view>
        </view>

        <!-- 重复信息 -->
        <view v-if="event.repeatType && event.repeatType !== 'none'" class="detail-item">
          <view class="detail-icon">🔄</view>
          <view class="detail-content">
            <text class="detail-label">重复</text>
            <text class="detail-value">{{ getRepeatTypeText(event.repeatType) }}</text>
          </view>
        </view>

        <!-- 状态信息 -->
        <view class="detail-item">
          <view class="detail-icon">📊</view>
          <view class="detail-content">
            <text class="detail-label">状态</text>
            <view class="status-badge" :class="'status-' + event.status">
              <text class="status-text">{{ getStatusText(event.status) }}</text>
            </view>
          </view>
        </view>

        <!-- 创建时间 -->
        <view class="detail-item">
          <view class="detail-icon">📅</view>
          <view class="detail-content">
            <text class="detail-label">创建时间</text>
            <text class="detail-value">{{ formatDateTime(event.createdAt) }}</text>
          </view>
        </view>
      </view>

      <!-- 操作按钮 -->
      <view class="action-buttons">
        <button class="edit-btn" @click="editEvent">
          <text class="btn-icon">✏️</text>
          <text class="btn-text">编辑</text>
        </button>
        <button class="delete-btn" @click="showDeleteConfirm">
          <text class="btn-icon">🗑️</text>
          <text class="btn-text">删除</text>
        </button>
      </view>
    </view>

    <!-- 删除确认弹窗 -->
    <view v-if="showDeleteModal" class="modal-overlay" @click="hideDeleteConfirm">
      <view class="modal-content" @click.stop>
        <view class="modal-header">
          <text class="modal-title">确认删除</text>
        </view>
        <view class="modal-body">
          <text class="modal-text">确定要删除事件"{{ event?.title }}"吗？</text>
          <text class="modal-subtitle">删除后无法恢复</text>
        </view>
        <view class="modal-actions">
          <button class="modal-btn cancel-btn" @click="hideDeleteConfirm">取消</button>
          <button class="modal-btn confirm-btn" @click="confirmDelete" :disabled="deleting">
            {{ deleting ? '删除中...' : '确定删除' }}
          </button>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import { mapActions } from 'vuex'

export default {
  name: 'EventDetail',
  data() {
    return {
      eventId: null,
      event: null,
      loading: true,
      error: null,
      showDeleteModal: false,
      deleting: false
    }
  },
  onLoad(options) {
    if (options.id) {
      this.eventId = options.id
      this.loadEventDetail()
    } else {
      this.error = '缺少事件ID参数'
      this.loading = false
    }
  },
  methods: {
    ...mapActions('calendar', ['getEventDetail', 'deleteEvent']),

    async loadEventDetail() {
      try {
        this.loading = true
        this.error = null
        console.log('Loading event detail for ID:', this.eventId)
        
        const eventData = await this.getEventDetail(this.eventId)
        this.event = eventData
        console.log('Event data loaded:', eventData)
      } catch (error) {
        console.error('加载事件详情失败:', error)
        this.error = error.message || '加载事件详情失败'
      } finally {
        this.loading = false
      }
    },

    editEvent() {
      // 跳转到编辑页面（可以复用add-event页面）
      uni.navigateTo({
        url: `/pages/calendar/add-event?id=${this.eventId}&mode=edit`
      })
    },

    showDeleteConfirm() {
      this.showDeleteModal = true
    },

    hideDeleteConfirm() {
      this.showDeleteModal = false
    },

    async confirmDelete() {
      try {
        this.deleting = true
        await this.deleteEvent(this.eventId)
        
        uni.showToast({
          title: '删除成功',
          icon: 'success'
        })
        
        // 延迟返回上一页
        setTimeout(() => {
          uni.navigateBack()
        }, 1500)
      } catch (error) {
        console.error('删除事件失败:', error)
        uni.showToast({
          title: '删除失败',
          icon: 'none'
        })
      } finally {
        this.deleting = false
        this.showDeleteModal = false
      }
    },

    // 格式化日期相关方法
    formatDay(dateStr) {
      if (!dateStr) return ''
      const date = new Date(dateStr)
      return date.getDate().toString().padStart(2, '0')
    },

    formatMonth(dateStr) {
      if (!dateStr) return ''
      const date = new Date(dateStr)
      const months = ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月']
      return months[date.getMonth()]
    },

    formatEventTime(event) {
      if (!event) return ''
      
      if (event.isAllDay) {
        return '全天'
      }
      
      let timeStr = this.formatDate(event.eventDate)
      
      if (event.startTime) {
        timeStr += ` ${event.startTime}`
        if (event.endTime) {
          timeStr += ` - ${event.endTime}`
        }
      }
      
      return timeStr
    },

    formatDate(dateStr) {
      if (!dateStr) return ''
      const date = new Date(dateStr)
      return `${date.getFullYear()}年${date.getMonth() + 1}月${date.getDate()}日`
    },

    formatDateTime(dateTimeStr) {
      if (!dateTimeStr) return ''
      const date = new Date(dateTimeStr)
      return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')} ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`
    },

    formatReminderText(minutes) {
      if (!minutes || minutes === 0) return '无提醒'
      if (minutes < 60) return `提前${minutes}分钟`
      if (minutes < 1440) return `提前${Math.floor(minutes / 60)}小时`
      return `提前${Math.floor(minutes / 1440)}天`
    },

    getEventTypeText(type) {
      const typeMap = {
        birthday: '生日',
        anniversary: '纪念日',
        holiday: '节日',
        meeting: '聚会',
        other: '其他'
      }
      return typeMap[type] || '其他'
    },

    getRepeatTypeText(type) {
      const repeatMap = {
        none: '不重复',
        daily: '每天',
        weekly: '每周',
        monthly: '每月',
        yearly: '每年'
      }
      return repeatMap[type] || '不重复'
    },

    getStatusText(status) {
      const statusMap = {
        active: '活跃',
        cancelled: '已取消',
        completed: '已完成'
      }
      return statusMap[status] || '未知'
    }
  }
}
</script>

<style lang="scss" scoped>
.page-container {
  min-height: 100vh;
  background-color: #f5f5f5;
}

// 加载状态
.loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100vh;
  
  .loading-spinner {
    width: 60rpx;
    height: 60rpx;
    border: 4rpx solid #e1e1e1;
    border-top: 4rpx solid #007AFF;
    border-radius: 50%;
    animation: spin 1s linear infinite;
  }
  
  .loading-text {
    margin-top: 20rpx;
    font-size: 28rpx;
    color: #666;
  }
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

// 错误状态
.error-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100vh;
  padding: 40rpx;
  
  .error-icon {
    font-size: 80rpx;
    margin-bottom: 20rpx;
  }
  
  .error-text {
    font-size: 32rpx;
    color: #666;
    text-align: center;
    margin-bottom: 40rpx;
  }
  
  .retry-btn {
    background-color: #007AFF;
    color: white;
    border: none;
    border-radius: 8rpx;
    padding: 20rpx 40rpx;
    font-size: 28rpx;
  }
}

// 事件详情
.event-detail {
  padding: 0;
}

.event-header {
  background: linear-gradient(135deg, #007AFF 0%, #5856D6 100%);
  padding: 60rpx 40rpx 40rpx;
  color: white;
  
  .event-date-section {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 30rpx;
    
    .event-date {
      display: flex;
      flex-direction: column;
      align-items: center;
      background: rgba(255, 255, 255, 0.2);
      border-radius: 16rpx;
      padding: 20rpx;
      min-width: 120rpx;
      
      .date-day {
        font-size: 48rpx;
        font-weight: bold;
      }
      
      .date-month {
        font-size: 24rpx;
        margin-top: 4rpx;
        opacity: 0.8;
      }
    }
    
    .event-type-badge {
      background-color: rgba(255, 255, 255, 0.3);
      border-radius: 20rpx;
      padding: 12rpx 24rpx;
      
      .type-text {
        font-size: 24rpx;
        font-weight: 500;
      }
    }
  }
  
  .event-title-section {
    .event-title {
      font-size: 36rpx;
      font-weight: bold;
      margin-bottom: 12rpx;
      display: block;
    }
    
    .event-description {
      font-size: 28rpx;
      opacity: 0.9;
      line-height: 1.4;
      display: block;
    }
  }
}

.event-details {
  background: white;
  margin: 20rpx;
  border-radius: 16rpx;
  padding: 0;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
  
  .detail-item {
    display: flex;
    align-items: center;
    padding: 32rpx;
    border-bottom: 1rpx solid #f0f0f0;
    
    &:last-child {
      border-bottom: none;
    }
    
    .detail-icon {
      font-size: 32rpx;
      width: 60rpx;
      text-align: center;
      margin-right: 24rpx;
    }
    
    .detail-content {
      flex: 1;
      
      .detail-label {
        font-size: 24rpx;
        color: #666;
        margin-bottom: 8rpx;
        display: block;
      }
      
      .detail-value {
        font-size: 28rpx;
        color: #333;
        font-weight: 500;
        display: block;
      }
      
      .status-badge {
        display: inline-block;
        padding: 8rpx 16rpx;
        border-radius: 12rpx;
        font-size: 24rpx;
        
        &.status-active {
          background-color: #e8f5e8;
          color: #34c759;
        }
        
        &.status-cancelled {
          background-color: #ffeaea;
          color: #ff3b30;
        }
        
        &.status-completed {
          background-color: #e8f4fd;
          color: #007AFF;
        }
      }
    }
  }
}

.action-buttons {
  display: flex;
  gap: 20rpx;
  padding: 40rpx;
  
  button {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 12rpx;
    padding: 28rpx;
    border-radius: 12rpx;
    font-size: 28rpx;
    font-weight: 500;
    border: none;
    
    .btn-icon {
      font-size: 32rpx;
    }
  }
  
  .edit-btn {
    background-color: #007AFF;
    color: white;
    
    &:active {
      background-color: #0051D5;
    }
  }
  
  .delete-btn {
    background-color: #ff3b30;
    color: white;
    
    &:active {
      background-color: #d70015;
    }
  }
}

// 删除确认弹窗
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.modal-content {
  background: white;
  border-radius: 16rpx;
  margin: 40rpx;
  max-width: 600rpx;
  width: 100%;
  
  .modal-header {
    padding: 40rpx 40rpx 20rpx;
    text-align: center;
    
    .modal-title {
      font-size: 32rpx;
      font-weight: bold;
      color: #333;
    }
  }
  
  .modal-body {
    padding: 20rpx 40rpx 40rpx;
    text-align: center;
    
    .modal-text {
      font-size: 28rpx;
      color: #333;
      margin-bottom: 12rpx;
      display: block;
    }
    
    .modal-subtitle {
      font-size: 24rpx;
      color: #999;
      display: block;
    }
  }
  
  .modal-actions {
    display: flex;
    border-top: 1rpx solid #f0f0f0;
    
    .modal-btn {
      flex: 1;
      padding: 32rpx;
      font-size: 28rpx;
      border: none;
      background: none;
      
      &.cancel-btn {
        color: #666;
        border-right: 1rpx solid #f0f0f0;
        
        &:active {
          background-color: #f8f8f8;
        }
      }
      
      &.confirm-btn {
        color: #ff3b30;
        font-weight: 500;
        
        &:active {
          background-color: #f8f8f8;
        }
        
        &:disabled {
          color: #ccc;
        }
      }
    }
  }
}
</style> 